/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package servlet;

import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.panel.Category;

import java.sql.*;
import handler.database;
/**
 *
 * @author SONY VAIO
 */
public class CategoryPanelServlet extends HttpServlet {

    ArrayList<Category> categorys;

    public void init() throws ServletException{
        super.init();
    }

    private void getDatabaseCategory() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
        Connection conn = null;
        database db = new database();
        conn = db.getConnection();

        String strQuery = "SELECT * from category WHERE parent_id="+0;
        Statement statement = conn.createStatement();
        ResultSet result = statement.executeQuery(strQuery);

        System.out.println(strQuery);

        while(result.next()){
            System.out.println("TES");
            int id = Integer.parseInt(result.getString(1));
            String categoryName = result.getString(2);
            int ownerId = Integer.parseInt(result.getString(3));
            int parentId = Integer.parseInt(result.getString(4));
            if(ownerId!=0) {
                String strQuery1 = "SELECT * from user WHERE id="+ownerId;
                Statement statement1 = conn.createStatement();
                ResultSet result1 = statement1.executeQuery(strQuery1);

                while(result1.next()){
                    String ownerName = result1.getString(2);
                    Category category = new Category(id, categoryName, ownerId, parentId, ownerName);
                    categorys.add(category);
                }
            } else {
                Category category = new Category(id, categoryName, ownerId, parentId, "none");
                    categorys.add(category);
            }
            
            
        }
        conn.close();
    }

    private void deleteDatabaseCategory(String name) throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
        
        Connection conn = null;
        database db = new database();
        conn = db.getConnection();

        String strQuery1 = "SELECT * FROM category WHERE name = '"+ name +"'" ;
        Statement statement1 = conn.createStatement();
        ResultSet result1 = statement1.executeQuery(strQuery1);
        while(result1.next()){
            int parentId = Integer.parseInt(result1.getString(1));

            String strQuery2 = "DELETE FROM category WHERE parent_id="+ parentId;
            Statement statement2 = conn.createStatement();
            int result2 = statement2.executeUpdate(strQuery2);

            System.out.println(strQuery2);
        }

        String strQuery = "DELETE FROM category WHERE name = '"+ name +"'" ;
        Statement statement = conn.createStatement();
        int result = statement.executeUpdate(strQuery);

        System.out.println(strQuery);
    }
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        if(request.getParameter("action").toString().equalsIgnoreCase("get"))
        {
            categorys = new ArrayList<Category>();
            try {
                getDatabaseCategory();
            } catch (SQLException ex) {
                Logger.getLogger(CategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                Logger.getLogger(CategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(CategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(CategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            }

            try{
                Gson gson = new Gson();
                String stringCategory = gson.toJson(categorys);
                System.out.println(stringCategory);
                out.println(stringCategory);
            }finally {
                out.close();
            }
        } else if(request.getParameter("action").toString().equalsIgnoreCase("delete")){
            try { 
                String category_name = request.getParameter("name").toString();
                deleteDatabaseCategory(category_name);
            } catch (SQLException ex) {
                Logger.getLogger(CategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                Logger.getLogger(CategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(CategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(CategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            }finally {
                out.close();
            }
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
